<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>消息中心</title>
  <style>
    .demo-form-inline {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 4rem;
    }

    .user_box {
      width: 90%;
      height: 50px;
      background: white;
      display: flex;
      justify-content: space-between;
      align-items: center;
      cursor: pointer;
    }

    .user_box:hover {
      background-color: #f8f8f8;
    }

    .content_box {
      width: 100%;
      height: 70vh;
      background-color: white;
      box-shadow: 0px -2px 5px 2px gainsboro;
      overflow: auto;
      scroll-behavior: smooth;
    }

    .dialog {
      width: 100%;
      float: left;
    }

    .send_msg {
      background-color: #f8f8f8;
      word-wrap: break-word;
      border-radius: 10px;
      padding: 15px;
      margin: 30px;
      position: relative;
      float: left;
    }

    .send_msg::before {
      content: "";
      position: absolute;
      top: 50%;
      left: -10px;
      /* 调整三角形的位置使底部紧贴在盒子的左边 */
      transform: translateY(-50%);
      width: 0;
      height: 0;
      border-top: 10px solid transparent;
      border-bottom: 10px solid transparent;
      border-right: 10px solid #f8f8f8;
    }

    .recive_msg::before {
      content: "";
      position: absolute;
      right: -20px;
      /* 使三角形指向右侧 */
      top: 50%;
      transform: translateY(-50%);
      border-width: 10px;
      border-style: solid;
      border-color: transparent transparent transparent #ccf3f2;
    }

    .recive_msg {
      position: relative;
      background-color: #ccf3f2;
      word-wrap: break-word;
      border-radius: 10px;
      padding: 15px;
      margin: 30px;
      float: right;
    }

    .message_box {
      width: 100%;
      height: 100%;
    }

    .search_box {
      margin-bottom: 2vh;
    }

    .user_list {
      width: 80%;
      height: 100%;
      border-right: gainsboro 1px solid;
    }

    .icon_box {
      width: 50%;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }

    .send_box {
      width: 100%;
      height: 10vh;
      box-shadow: -2px 2px 10px 2px gainsboro;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .icon {
      margin-left: 20px;
      margin-right: 20px;
    }
  </style>
  <link rel="stylesheet" href="../plugins/elementui/index.css">
  <!--    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">-->
  <script src="../js/vue.js"></script>
  <script src="../plugins/elementui/index.js"></script>
  <script src="../js/axios-0.18.0.js"></script>
</head>

<body>
  <div id="app">
    <div class="content">
      <div class="search_box">
        <el-form :inline="true" :model="userInfo" class="demo-form-inline">
          <el-form-item>
            <el-input v-model="userInfo.account" placeholder="用户名" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="query">查询</el-button>
          </el-form-item>
        </el-form>
      </div>

      <div style="width: 97%">
        <el-container>
          <el-aside width="20%">
            <div class="user_list">
              <div class="user_box" v-for="(item, index) in userList" :key="index" @click="toCommunicate(item.id)">
                <span style="font-size: small">{{ item.account }}</span>
                <div class="icon_box">
                  <!--                                <el-icon color="red" v-if="item.readCount !== 0 && read=false">-->
                  <!--                                    <BellFilled/>-->
                  <!--                                </el-icon>-->
                  <el-icon>
                    <ArrowRight />
                  </el-icon>
                </div>
              </div>
            </div>
          </el-aside>
          <el-main>
            <div class="content_box" v-show="sendData.receiverId" ref="messageBox">
              <div class="message_box">
                <div class="dialog" v-for="(item, index) in messageList" :key="index">
                  <div :class="
                    item.receiverId == 1
                      ? 'send_msg'
                      : 'recive_msg'
                  " v-if="
                    (item.senderId == 1 &&
                      item.receiverId == clickUserId) ||
                    item.senderId == clickUserId
                  ">
                    <span v-if="item.messageType !== 'img'">{{
                      item.messageText
                      }}</span>
                    <el-image :preview-src-list="[item.messageText]" style="width: 100px; height: 100px" v-else
                      :src="item.messageText" :fit="fit" />
                  </div>
                </div>
              </div>
            </div>
            <div class="send_box" v-show="sendData.receiverId">
              <div style="width: 50%">
                <el-input placeholder="请输入需要发送的消息" v-model="sendData.messageText"
                  @keyup.enter.native="sendMsg"></el-input>
              </div>
              <el-upload class="avatar-uploader" action="https://www.twiceok.com/feignService/upload"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon class="icon">
                  <CirclePlus />
                </el-icon>
              </el-upload>

              <el-button type="primary" @click="sendMsg">发送</el-button>
            </div>
          </el-main>
        </el-container>
      </div>
    </div>
  </div>

  <script>
    axios.defaults.baseURL = "";
    axios.defaults.timeout = 1000;
    axios.interceptors.request.use(
      config => {
        config.headers['authorization'] = 'admin'
        return config
      },
      error => {
        console.log(error)
        Promise.reject(error)
      }
    )

    const app = new Vue({
      el: "#app",
      data: {
        pagination: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
          queryString: null,
          pageNo: 1
        },
        pageSize: 5,
        pageSizes: [5, 10, 20, 50, 100, 200],
        isEdit: false,
        lastPage: 1,
        // 用户信息
        userList: [],
        socket: '',
        messageList: [],
        messageBox: {
          scrollTop: 0
        },
        userInfo: {
          account: ''
        },
        sendData: {
          messageText: "",
          senderId: "",
          receiverId: "",
          messageType: ''
        },
        clickUserId: '',
        imageUrl: ''
      },
      created() {
        this.query()
        this.openSocket()
      },
      watch: {
        pageSize() {
          this.query(1);
        }
      },
      methods: {
        beforeAvatarUpload() {

        },
        async toCommunicate(userId) {
          this.sendData.receiverId = userId;
          this.sendData.senderId = 1;
          this.clickUserId = userId;
          this.sendData.messageText = "";
          this.read = true;
          this.scrollToBottom();
        },

        sendMsg() {
          if (!this.sendData.messageText.trim()) {
            return;
          }
          this.socket.send(JSON.stringify(this.sendData));
          this.sendData.messageText = "";
          this.scrollToBottom();
        },

        handleAvatarSuccess() {
          this.sendData.receiverId = clickUserId.value;
          this.sendData.senderId = store.state.userInfo.id;
          this.sendData.messageText = res
          this.sendData.messageType = 'img'
          this.socket.send(JSON.stringify(sendData.value));
          this.sendData.messageText = ''
        },
        async openSocket() {
          const res = await axios.get('/com/get')
          const self = this
          this.socket = new WebSocket(
            `ws://localhost:80/message/${res.data.data.id}`
          );
          this.socket.onopen = () => {
            console.log("WebSocket connected");
          };
          this.socket.onclose = function (e) {
            console.log("websocket 断开:" + e.code + e.reason + e.wasClean);
          };

          this.socket.onmessage = function (event) {
            self.messageList = JSON.parse(event.data);
            self.scrollToBottom();
          };

          this.socket.onerror = function (error) {
            console.error("WebSocket error:", error);
          };
        },
        findSearchPage() {
          this.lastPage = 1;
          this.query();
        },
        handleSizeChange(s) {
          this.pageSize = s;
        },
        query(page) {
          this.lastPage = page;
          axios.get("/users/list", {
            params: {
              pageNo: this.lastPage ? this.lastPage : 1,
              pageSize: this.pageSize,
            }
          })
            .then(resp => {
              this.userList = resp.data.data;
            })
            .catch(err => {
              console.log(err)
            });
        },
        handleEdit(v1, v2) {
          this.isEdit = true;
          this.order = JSON.parse(JSON.stringify(v2));
          this.formVisible = true;
        },
        handleDelete(v1, v2) {
          this.$confirm('此操作将永久删除订单信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteById(v2.order_id);
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        },
        async saveOrUpdate() {
          const data = new FormData()
          for (const key in this.order) {
            data.append(key, this.order[key])
          }
          const res = await axios.post("/orders/saveOrUpdate", data)
          const { code, msg } = res.data
          if (code !== 200) {
            this.$message({
              message: msg,
              type: 'error'
            });
            return
          }
          this.$message({
            message: '操作成功',
            type: 'success'
          });
        },
        deleteById(id) {
          axios.delete("/orders/" + id)
            .then(() => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.reload();
            })
            .catch(err => {
              this.$message({
                type: 'error',
                message: '删除失败!'
              });
              console.log(err);
            })
        },
        reload() {
          this.query(this.lastPage);
        },
        scrollToBottom() {
          this.$nextTick(() => {
            const messageBox = this.$refs.messageBox;
            if (messageBox) {
              messageBox.scrollTop = messageBox.scrollHeight;
            }
          });
        }
      }
    })
  </script>
</body>

</html>